package com.bootdo.app.alipay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.app.alipay.config.AlipayConfig;
import com.bootdo.app.alipay.service.EmpowerService;
import com.bootdo.app.alipay.util.AlipayUtil;
import com.bootdo.common.configure.dao.DictDao;
import com.bootdo.common.configure.domain.DictDO;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.payee.dao.PayeeDao;
import com.bootdo.payee.dao.PaymentCodeDao;
import com.bootdo.payee.domain.PayeeDO;
import com.bootdo.payee.domain.PaymentCodeDO;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class EmpowerServiceImpl implements EmpowerService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${alipay.callbackUrl}")
    private String callbackUrl;
    @Autowired
    private PayeeDao payeeMapper;
    @Autowired
    private DictDao dictMapper;
    @Autowired
    private PaymentCodeDao paymentCodeMapper;

    @Override
    public R alipayTranAccSave(PaymentCodeDO paymentCode) throws Exception {

        Map<String,String> alipayMap = new HashMap<String,String>();
        alipayMap.put("userIdCreate",paymentCode.getUserIdCreate().toString());
        alipayMap.put("belongPassageway",paymentCode.getBelongPassageway().toString());
        String state = Base64.encodeBase64String(JSONObject.toJSONString(alipayMap).getBytes());
        //重定向到授权页面
        String qrCodeUrl = AlipayConfig.ALIPAY_URL + "?app_id=" + AlipayConfig.APP_ID
                + "&scope=auth_user&redirect_uri=" + URLEncoder.encode(callbackUrl, "UTF-8")
                + "&state=" + state;
        String jumpUrl = URLEncoder.encode(qrCodeUrl, "UTF-8");
        Map<String, String> map = new HashMap<>();
        map.put("jumpUrl", jumpUrl);
        map.put("qrCodeUrl", qrCodeUrl);
        return R.ok(map);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public void callbackTraAccSave(HttpServletRequest request) throws Exception {
        //获取支付宝GET过来反馈信息
        String authCode = request.getParameter("auth_code");
        String authToken= AlipayUtil.buildRequest(authCode);
        String userInfo = null;
        if(StringUtils.isEmpty(authToken)){
            logger.error(">>>>>>>>>>callbackTraAccSave接口authToken:{}<<<<<<<<<<",authToken);
            throw new Exception("支付宝转账新增错误");
        }else {
            userInfo  =  AlipayUtil.get(authToken);
            logger.info(">>>>>>>>>>callbackTraAccSave接口userInfo:{}<<<<<<<<<<",userInfo);
        }
        JSONObject userInfoJsonObject = JSONObject.parseObject(userInfo);
        String alipayUserInfoShareResponse = userInfoJsonObject.getString("alipay_user_info_share_response");
        JSONObject jsonObj = JSONObject.parseObject(alipayUserInfoShareResponse);
        if(!"10000".equals(jsonObj.getString("code"))){
            throw new Exception(jsonObj.getString("msg"));
        }

        String state = request.getParameter("state");
        String json = new String(Base64.decodeBase64(state));
        JSONObject jsonObject = JSONObject.parseObject(json);

        PaymentCodeDO paymentCode = new PaymentCodeDO();
        Date date = new Date();
        paymentCode.setUserIdCreate(Long.valueOf(jsonObject.getString("userIdCreate")));
        paymentCode.setPassagewayId(3);
        paymentCode.setGmtCreate(date);
        paymentCode.setReceivingAccount(1);
        paymentCode.setQrCode(jsonObj.getString("user_id"));
        paymentCode.setAuditStatus("1");
        String nickName = jsonObj.getString("nick_name");
        if (StringUtils.isBlank(nickName)){
            PayeeDO payee = payeeMapper.get(Long.valueOf(jsonObject.getString("userIdCreate")));
            nickName = payee.getName() + StringUtils.getUUIDStr(4);
        }
        paymentCode.setPayeeName(nickName);
        paymentCode.setBelongPassageway(Long.valueOf(jsonObject.getString("belongPassageway")));

        int count = paymentCodeMapper.paymentCodeSave(paymentCode);
        if(count != 1){
            logger.error(">>>>>>>>>>callbackTraAccSave接口count:{}<<<<<<<<<<",count);
            throw new Exception("支付宝转账新增错误");
        }

        Long codeId = paymentCode.getCodeId();
        PaymentCodeDO paymentCodeDO = new PaymentCodeDO();
        paymentCodeDO.setCodeId(codeId);
        paymentCodeDO.setUserIdCreate(Long.valueOf(jsonObject.getString("userIdCreate")));
        paymentCodeDO.setGmtModified(date);
        paymentCodeDO.setBelongPassageway(Long.valueOf(jsonObject.getString("belongPassageway")));
        int i = paymentCodeMapper.closeUserPassagewayOtherCode(paymentCodeDO);
        if(i < 0){
            logger.error(">>>>>>>>>>callbackTraAccSave接口i:{}<<<<<<<<<<",i);
            throw new Exception("支付宝转账新增错误");
        }
    }


}
